package com.lihua.project.taskcenter.core.init;

import com.lihua.common.utils.CacheUtils;
import com.lihua.project.taskcenter.core.match.ITaskMatchRule;
import com.lihua.project.taskcenter.core.utils.TaskListUtils;
import com.lihua.project.taskcenter.taskcenter.domain.Task;
import com.lihua.project.taskcenter.taskcenter.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

import java.util.List;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author lihua
 * @date 2022/3/16 16:21
 * 任务匹配初始化
 * 1、项目启动时去数据库拉取未匹配成功的任务
 * 2、定期拉取数据库未匹配成功的任务，刷新缓存，防止匹配异常
 */
@Component
@Slf4j
public class TaskMatchInit {

    @Autowired
    private ITaskService taskService;

    /**必须指定注入哪个匹配实现类*/
    @Autowired
    @Qualifier("DefaultTaskMatchRule")
    private ITaskMatchRule taskMatchRule;


    @PostConstruct
    public void init(){
        //获取数据库中所有没有匹配的任务
        List<Task> taskList = taskService.selectTaskByStatus("1");
        log.debug("taskList={}",taskList);
        CacheUtils.put("taskCache","taskMatch",taskList);
        CacheUtils.put("taskCache","taskMatchSize",taskList.size());
        //启动匹配线程
        ScheduledExecutorService matchJob = Executors.newScheduledThreadPool(5);
        matchJob.scheduleAtFixedRate(()->{
            taskMatchRule.matching(TaskListUtils.getTaskAll());
            //缓存当前匹配的任务数
            CacheUtils.put("taskCache","taskMatchSize",TaskListUtils.getTaskAll().size());
        },60,10, TimeUnit.SECONDS);
    }
}
